package com.siwei.mes.service.erp.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.siwei.mes.common.query.PageQuery;
import com.siwei.mes.common.util.DateHelper;
import com.siwei.mes.common.util.JsonUtils;
import com.siwei.mes.common.util.NullUtils;
import com.siwei.mes.common.util.StringHelperUtils;
import com.siwei.mes.config.UidUtils;
import com.siwei.mes.entity.dto.OpenAppraisalDto;
import com.siwei.mes.entity.dto.PrintRwdextraExperimentInfo;
import com.siwei.mes.entity.erp.*;
import com.siwei.mes.entity.experiment.Experiment;
import com.siwei.mes.entity.experiment.ExperimentDetail;
import com.siwei.mes.entity.experiment.OpenAppraisal;
import com.siwei.mes.entity.experiment.concrete.batch.ConcreteKsdj;
import com.siwei.mes.entity.experiment.concrete.batch.ConcreteKyqd;
import com.siwei.mes.entity.experiment.concrete.batch.ConcreteKzqd;
import com.siwei.mes.entity.experiment.concrete.batch.ConcreteXnbgLlzhl;
import com.siwei.mes.entity.mixproportion.MixProportion;
import com.siwei.mes.entity.mixproportion.MixProportionReport;
import com.siwei.mes.enums.CheckEnum;
import com.siwei.mes.enums.GenerateCodeEnum;
import com.siwei.mes.enums.KsLqEnum;
import com.siwei.mes.enums.TestProjectEnum;
import com.siwei.mes.mapper.erp.ItemorderMapper;
import com.siwei.mes.mapper.erp.RwdextraExtendMapper;
import com.siwei.mes.mapper.erp.RwdextraMapper;
import com.siwei.mes.mapper.experiment.ExperimentDetailMapper;
import com.siwei.mes.mapper.experiment.ExperimentMapper;
import com.siwei.mes.mapper.experiment.OpenAppraisalMapper;
import com.siwei.mes.mapper.mixProportion.MixProportionMapper;
import com.siwei.mes.mapper.system.SignatureMapper;
import com.siwei.mes.service.erp.*;
import com.siwei.mes.service.experiment.OpenAppraisalService;
import com.siwei.mes.service.laboratory.TaskListLaboratoryService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

import static com.siwei.mes.common.exception.handler.MessageHandler.assertTrue;

/**
 * ERP-生产任务(Rwdextra)表服务实现类
 *
 * @author linzi
 * @since 2024-07-29 16:13:33
 */
@Service
public class RwdextraServiceImpl implements RwdextraService {
    private static final Logger log = LoggerFactory.getLogger("erp");
    @Resource
    private RwdextraMapper rwdextraMapper;
    @Resource
    private RwdextraExtendMapper rwdextraExtendMapper;
    @Resource
    private TaskListLaboratoryService taskListLaboratoryService;
    @Resource
    private RwdextraExtendService rwdextraExtendService;
    @Resource
    private ContractService contractService;
    @Resource
    private ContractrelationService contractrelationService;
    @Resource
    private ExperimentMapper experimentMapper;
    @Resource
    private ExperimentDetailMapper experimentDetailMapper;
    @Resource
    private OpenAppraisalMapper openAppraisalMapper;
    @Resource
    private OpenAppraisalService openAppraisalService;
    @Resource
    private MixProportionMapper mixProportionMapper;
    @Resource
    private PhbhistoryService phbhistoryService;
    @Resource
    private SignatureMapper signatureMapper;
    @Resource
    private ItemorderMapper itemorderMapper;

    @Override
    public PageInfo<Rwdextra> getPage(PageQuery<Rwdextra, Rwdextra> query) {
        Rwdextra searchParam = query.getParams();
        searchParam.setFrwno(StringHelperUtils.trimString(searchParam.getFrwno()));
        PageInfo<Rwdextra> pageInfo = PageHelper.startPage(query.getPageNum(), query.getPageSize())
                .doSelectPageInfo(() -> rwdextraMapper.getList(searchParam));

        List<Rwdextra> list = pageInfo.getList();
        if (list.isEmpty()) {
            return pageInfo;
        }
        this.payloadOtherInfoList(pageInfo.getList());
        return pageInfo;
    }

    /**
     * 组装其它信息
     *
     * @param list
     */
    private void payloadOtherInfoList(List<Rwdextra> list) {
        if (list.isEmpty()) {
            return;
        }
        /**这里获取所有的任务单唯一标识*/
        Set<Integer> frwdList = new HashSet<>();
        for (Rwdextra rwdextra : list) {
            frwdList.add(rwdextra.getFrwdh());
        }

        /**查询所有品控扩展信息*/
        Map<Integer, RwdextraExtend> rwdextraExtendMap = rwdextraExtendService.getRwdextraExtendMap(frwdList);
        /**查询所有ERP的合同信息*/
        Map<Integer, Contract> contractMap = contractService.getContractMap(frwdList);
        /**查询所有ERP的工程信息*/
        Map<Integer, Contractrelation> contractrelationMap = contractrelationService.getContractrelationMap(frwdList);

        for (Rwdextra rwdextra : list) {
            try {
                Integer frwdh = rwdextra.getFrwdh();
                /**组装返回任务单信息*/
                RwdextraInfo rwdextraInfo = RwdextraInfo.jsonToObj(rwdextra.getExtrainfo());
                if (rwdextraInfo != null) {
                    rwdextra.setRwdextraInfo(rwdextraInfo);
                    rwdextra.setFrwno(rwdextraInfo.getFRwno());
                    rwdextra.setFzt(rwdextraInfo.getFZt());
                    rwdextra.setProjectNameNew(rwdextraInfo.getFGcmc());
                    rwdextra.setBuildNameNew(rwdextraInfo.getFHtdw());
                    rwdextra.setJzbw(rwdextraInfo.getFJzbw());
                }

                /**这里查询erp合同信息*/
                Contract contract = contractMap.get(frwdh);
                if (contract != null && contract.getContractExtraInfo() != null) {
                    ContractExtraInfo contractExtraInfo = contract.getContractExtraInfo();
                    rwdextra.setContractName(contractExtraInfo.getContractName());
                    rwdextra.setContractNameNew(contractExtraInfo.getContractName());
                }

                /**这里查询erp工程信息*/
                Contractrelation contractrelation = contractrelationMap.get(frwdh);
                if (contractrelation != null) {
                    rwdextra.setProjectNameNew(contractrelation.getProjectname());
                    rwdextra.setProjectLinkMan(contractrelation.getLinkman());
                    rwdextra.setProjectLinkTel(contractrelation.getLinktel());
                    rwdextra.setProjectArea(contractrelation.getProjectarea());
                }

                /**这里查询品控扩展信息*/
                RwdextraExtend rwdextraExtend = rwdextraExtendMap.get(frwdh);
                if (rwdextraExtend != null) {
                    rwdextra.setProduceId(rwdextraExtend.getProduceId());
                    rwdextra.setProduceIndexId(rwdextraExtend.getProduceIndexId());
                    rwdextra.setConsignId(rwdextraExtend.getConsignId());
                    rwdextra.setPrintStatus(NullUtils.ifNullInteger(rwdextraExtend.getPrintStatus(), 0));
                    String projectName = rwdextraExtend.getProjectName();
                    String contractName = rwdextraExtend.getContractName();
                    String buildName = rwdextraExtend.getBuildName();
                    if (StringUtils.isNotBlank(projectName)) {
                        rwdextra.setProjectNameNew(projectName);
                    }
                    if (StringUtils.isNotBlank(contractName)) {
                        rwdextra.setContractNameNew(contractName);
                    }
                    if (StringUtils.isNotBlank(buildName)) {
                        rwdextra.setBuildNameNew(buildName);
                    }
                    rwdextra.setIsAddInformation(rwdextraExtend.getIsAddInformation());
                    rwdextra.setRwdextraExtend(rwdextraExtend);
                }
            } catch (Exception e) {
                log.error("组装ERP任务单其它信息失败，直接返回不做任何处理！");
            }
        }
    }

    @Override
    public Rwdextra loadByFrwdh(Integer frwdh) {
        Rwdextra rwdextra = rwdextraMapper.selectByFrwdh(frwdh);
        if (rwdextra != null) {
            this.payloadOtherInfoList(Collections.singletonList(rwdextra));
        }
        return rwdextra;
    }

    @Override
    public Rwdextra selectByPhbTop(String fPhbNo, String fGcmc, String year) {
        Rwdextra rwdextra = rwdextraMapper.selectByPhbTop(fPhbNo, fGcmc, year);
        if (rwdextra != null) {
            this.payloadOtherInfoList(Collections.singletonList(rwdextra));
        }
        return rwdextra;
    }

    @Override
    public List<Rwdextra> selectIronMarkInfo(List<String> projectNameList, String materialSpecs) {
        List<Rwdextra> rwdextraList = rwdextraMapper.selectIronMarkInfo(projectNameList, materialSpecs);
        this.payloadOtherInfoList(rwdextraList);
        return rwdextraList;
    }

    @Override
    public Rwdextra selectByRwNo(String rwNo) {
        Rwdextra rwdextra = rwdextraMapper.selectByRwNo(rwNo);
        if (rwdextra != null) {
            RwdextraInfo rwdextraInfo = RwdextraInfo.jsonToObj(rwdextra.getExtrainfo());
            rwdextra.setRwdextraInfo(rwdextraInfo);
            Integer fRwdh = rwdextra.getFrwdh();
            RwdextraExtend rwdextraExtend = rwdextraExtendMapper.selectByFRwdh(fRwdh);
            if (rwdextraExtend != null) {
                rwdextra.setRwdextraExtend(rwdextraExtend);
            } else {
                rwdextraExtend = new RwdextraExtend().setFrwdh(fRwdh);
                rwdextraExtendMapper.insertSelective(rwdextraExtend);
                rwdextra.setRwdextraExtend(rwdextraExtend);
            }
            /**组装其它信息*/
            this.payloadOtherInfoList(Collections.singletonList(rwdextra));
        }
        return rwdextra;
    }

    /**
     * 获取打印数据的试验信息
     *
     * @param experimentIdList 试验委托id集合
     * @return
     */
    private List<PrintRwdextraExperimentInfo.ExperimentInfoVo> getPrintExperimentInfoVo(List<Long> experimentIdList) {
        List<PrintRwdextraExperimentInfo.ExperimentInfoVo> list = new ArrayList<>();
        if (experimentIdList.isEmpty()) {
            return list;
        }
        for (Long experimentId : experimentIdList) {
            PrintRwdextraExperimentInfo.ExperimentInfoVo experimentInfo = new PrintRwdextraExperimentInfo.ExperimentInfoVo();
            Experiment experiment = experimentMapper.loadById(experimentId);
            if (experiment == null) {
                continue;
            }
            experimentInfo.setYpbh(experiment.getSampleId());
            experimentInfo.setSytzbh(String.valueOf(experimentId));
            experimentInfo.setSytzno(experiment.getExperimentNo());
            experimentInfo.setXhwtbh(experiment.getConsignId());
            list.add(experimentInfo);
        }
        return list;
    }

    /**
     * 获取打印数据的试验信息
     *
     * @param experimentId 试验委托id
     * @return
     */
    @Override
    public List<PrintRwdextraExperimentInfo.ExperimentInfoVo> getPrintExperimentInfoVo(Object experimentId) {
        List<PrintRwdextraExperimentInfo.ExperimentInfoVo> list = new ArrayList<>();
        if (experimentId == null) {
            return list;
        }
        List<Long> experimentIds = new ArrayList();
        if (experimentId instanceof List) {
            experimentIds = (List<Long>) experimentId;
        } else if (StringUtils.isNotBlank(experimentId.toString())) {
            experimentIds.add(Long.valueOf(experimentId.toString()));
        }
        for (Long experimentIdLong : experimentIds) {
            PrintRwdextraExperimentInfo.ExperimentInfoVo experimentInfo = new PrintRwdextraExperimentInfo.ExperimentInfoVo();
            Experiment experiment = experimentMapper.loadById(experimentIdLong);
            if (experiment == null) {
                return list;
            }
            experimentInfo.setYpbh(NullUtils.ifNull(experiment.getSampleId()));
            experimentInfo.setSytzbh(String.valueOf(experiment.getId()));
            experimentInfo.setSytzno(NullUtils.ifNull(experiment.getExperimentNo()));
            experimentInfo.setXhwtbh(NullUtils.ifNull(experiment.getConsignId()));
            list.add(experimentInfo);
        }
        return list;
    }

    @Override
    public PrintRwdextraExperimentInfo selectExperimentByFrwdh(Integer frwdh) {
        RwdextraExtend rwdextraExtend = rwdextraExtendMapper.selectByFRwdh(frwdh);
        if (rwdextraExtend != null) {
            RwdextraPrintInfo rwdextraPrintInfo = JsonUtils.getObject(rwdextraExtend.getPrintJson(), RwdextraPrintInfo.class);
            if (rwdextraPrintInfo != null) {
                PrintRwdextraExperimentInfo printRwdextraExperimentInfo = new PrintRwdextraExperimentInfo();
                List<Long> kyExperimentIdList = new ArrayList<>();
                if (rwdextraPrintInfo.getKyInfoList() != null && !rwdextraPrintInfo.getKyInfoList().isEmpty()) {
                    for (RwdextraPrintInfo.Kytz kytz : rwdextraPrintInfo.getKyInfoList()) {
                        if (StringUtils.isBlank(kytz.getSytzbh())) {
                            continue;
                        }
                        kyExperimentIdList.add(Long.valueOf(kytz.getSytzbh()));
                    }
                }

                printRwdextraExperimentInfo.setKyInfoList(this.getPrintExperimentInfoVo(kyExperimentIdList));
                printRwdextraExperimentInfo.setKsInfoList(this.getPrintExperimentInfoVo(rwdextraPrintInfo.getKsExperimentId()));
                printRwdextraExperimentInfo.setKzInfoList(this.getPrintExperimentInfoVo(rwdextraPrintInfo.getKzExperimentId()));
                printRwdextraExperimentInfo.setKllzInfoList(this.getPrintExperimentInfoVo(rwdextraPrintInfo.getKllExperimentId()));


                /**这里获取所有原材料的  之后在优化先完成功能*/
                MixProportion mixProportion = rwdextraPrintInfo.getMixProportionInfo();
                if (mixProportion != null && mixProportion.getProportionMaterial() != null) {
                    MixProportionReport mixProportionReport = JsonUtils.getObject(mixProportion.getProportionMaterial(), MixProportionReport.class);
                    if (mixProportionReport == null) {
                        return printRwdextraExperimentInfo;
                    }
                    if (mixProportionReport.getSn() != null) {
                        printRwdextraExperimentInfo.setSnInfoList(this.getPrintExperimentInfoVo(mixProportionReport.getSn().getPktzid()));
                    }
                    if (mixProportionReport.getXgl() != null) {
                        printRwdextraExperimentInfo.setXglInfoList(this.getPrintExperimentInfoVo(mixProportionReport.getXgl().getPktzid()));
                    }
                    if (mixProportionReport.getCgl() != null) {
                        printRwdextraExperimentInfo.setCglInfoList(this.getPrintExperimentInfoVo(mixProportionReport.getCgl().getPktzid()));
                    }
                    if (mixProportionReport.getFmh() != null) {
                        printRwdextraExperimentInfo.setFmhInfoList(this.getPrintExperimentInfoVo(mixProportionReport.getFmh().getPktzid()));
                    }
                    if (mixProportionReport.getKzf() != null) {
                        printRwdextraExperimentInfo.setKzfInfoList(this.getPrintExperimentInfoVo(mixProportionReport.getKzf().getPktzid()));
                    }
                    List<Long> wjjExperimentIdList = new ArrayList<>();
                    if (mixProportionReport.getWjj1() != null && StringUtils.isNotBlank(mixProportionReport.getWjj1().getPktzid())) {
                        wjjExperimentIdList.add(Long.valueOf(mixProportionReport.getWjj1().getPktzid()));
                    }
                    if (mixProportionReport.getWjj2() != null && StringUtils.isNotBlank(mixProportionReport.getWjj2().getPktzid())) {
                        wjjExperimentIdList.add(Long.valueOf(mixProportionReport.getWjj2().getPktzid()));
                    }
                    printRwdextraExperimentInfo.setWjjInfoList(this.getPrintExperimentInfoVo(wjjExperimentIdList));
                }
                return printRwdextraExperimentInfo;
            }
        }
        return new PrintRwdextraExperimentInfo();
    }

    @Override
    public RwdextraExtend loadByFrwdhExtend(Integer frwdh) {
        Rwdextra rwdextra = rwdextraMapper.selectByFrwdh(frwdh);
        if (rwdextra != null) {
            this.payloadOtherInfoList(Collections.singletonList(rwdextra));
        }
        RwdextraExtend rwdextraExtend = rwdextraExtendMapper.selectByFRwdh(frwdh);
        assertTrue(rwdextraExtend == null, "ERP任务单扩展信息不存在！");
        rwdextraExtend.setRwdextra(rwdextra);
        if (StringUtils.isBlank(rwdextraExtend.getPlanQuantity())) {
            rwdextraExtend.setPlanQuantity(rwdextra.getRwdextraInfo().getFJhsl());
        }
        if (StringUtils.isBlank(rwdextraExtend.getPouringPosition())) {
            rwdextraExtend.setPouringPosition(rwdextra.getRwdextraInfo().getFJzbw());
        }
        if (StringUtils.isBlank(rwdextraExtend.getProjectName())) {
            rwdextraExtend.setProjectName(rwdextra.getRwdextraInfo().getFGcmc());
        }
        rwdextraExtend.setFWcsl(rwdextra.getRwdextraInfo().getFWcsl());
        RwdextraPrintInfo rwdextraPrintInfo = JsonUtils.getObject(rwdextraExtend.getPrintJson(), RwdextraPrintInfo.class);
        if (rwdextraPrintInfo != null) {
            MixProportion mixProportion = rwdextraPrintInfo.getMixProportionInfo();
            rwdextraExtendService.setMixProportionPktzId(mixProportion, rwdextra);
            if (mixProportion != null) {
                rwdextraPrintInfo.setMixProportionInfo(mixProportion);
            }
            RwdextraPrintInfo.Customer customer = new RwdextraPrintInfo.Customer();
            if (rwdextraPrintInfo.getCustomer() != null) {
                customer = rwdextraPrintInfo.getCustomer();
            }
            if (StringUtils.isBlank(customer.getProjectName())) {
                customer.setProjectName(rwdextra.getRwdextraInfo().getFGcmc());
            }
            if (StringUtils.isBlank(customer.getCustomerName())) {
                customer.setCustomerName(rwdextra.getRwdextraInfo().getFHtdw());
            }
            if (StringUtils.isNotBlank(rwdextra.getRwdextraInfo().getFJhrq())) {
                customer.setPlantimeStart(DateHelper.fomatDate(rwdextra.getRwdextraInfo().getFJhrq()));
                rwdextraPrintInfo.setPlantimeStart(DateHelper.fomatDate(rwdextra.getRwdextraInfo().getFJhrq()));
                rwdextraExtend.setPlantimeStart(DateHelper.fomatDate(rwdextra.getRwdextraInfo().getFJhrq()));
            }
            rwdextraPrintInfo.setCustomer(customer);
            List<RwdextraPrintInfo.Kytz> kyList = rwdextraPrintInfo.getKyInfoList();
            List<String> kytzList = new ArrayList();
            List<Long> kyExperimentIdList = new ArrayList();
            if (kyList != null) {
                for (RwdextraPrintInfo.Kytz kytz : kyList) {
                    Long experimentId = Long.valueOf(kytz.getSytzbh());
                    Experiment experiment = experimentMapper.loadById(experimentId);
                    kytz.setYpbh(experiment.getSampleId());
                    kytz.setWtbh(experiment.getExperimentNo());
                    kytz.setXhwtbh(experiment.getConsignId());
                    if (StringUtils.isNotBlank(experiment.getSampleId())) {
                        kytzList.add(experiment.getSampleId());
                    } else {
                        kytzList.add(experiment.getExperimentNo());
                    }
                    kyExperimentIdList.add(experimentId);
                }
                rwdextraPrintInfo.setKyInfoList(kyList);
                rwdextraPrintInfo.setKytzList(kytzList);
            }
            if (rwdextraPrintInfo.getKsExperimentId() != null) {
                Long experimentId = Long.valueOf(rwdextraPrintInfo.getKsExperimentId());
                Experiment experiment = experimentMapper.loadById(experimentId);
                if (experiment != null) {
                    rwdextraPrintInfo.setKstzypbh(experiment.getSampleId());
                    rwdextraPrintInfo.setKstzwtbh(experiment.getExperimentNo());
                    /**试验台账对应试验项目信息*/
                    List<ExperimentDetail> experimentDetailList = experimentDetailMapper.selectByExperimentId(experimentId, TestProjectEnum.CONCRETE_PARAM_KSDJ.getCode());
                    if (CollectionUtil.isNotEmpty(experimentDetailList)) {
                        /**将json转成对象*/
                        ConcreteKsdj concreteKsdj = experimentDetailList.get(0).getObjJson().toJavaObject(ConcreteKsdj.class);
                        String ssksdj = concreteKsdj.getSsksdj();
                        String ksdj = rwdextra.getRwdextraInfo().getFTbj().split("|")[3];
                        if (org.apache.commons.lang3.StringUtils.isNotBlank(ksdj)) {
                            if (ssksdj.compareTo(ksdj) >= 0) {
                                rwdextraPrintInfo.setKstzjl("合格");
                            } else {
                                rwdextraPrintInfo.setKstzjl("不合格");
                            }
                        } else {
                            rwdextraPrintInfo.setKstzjl("合格");
                        }
                    }
                }
            }
            if (rwdextraPrintInfo.getKzExperimentId() != null) {
                Long experimentId = Long.valueOf(rwdextraPrintInfo.getKzExperimentId());
                Experiment experiment = experimentMapper.loadById(experimentId);
                if (experiment != null) {
                    rwdextraPrintInfo.setKztzypbh(experiment.getSampleId());
                    rwdextraPrintInfo.setKztzwtbh(experiment.getExperimentNo());
                    /**试验台账对应试验项目信息*/
                    List<ExperimentDetail> experimentDetailList = experimentDetailMapper.selectByExperimentId(experimentId, TestProjectEnum.CONCRETE_PARAM_KZQD.getCode());
                    if (CollectionUtil.isNotEmpty(experimentDetailList)) {
                        /**将json转成对象*/
                        ConcreteKzqd concreteKzqd = experimentDetailList.get(0).getObjJson().toJavaObject(ConcreteKzqd.class);
                        rwdextraPrintInfo.setKztzjl(concreteKzqd.getDxjl());
                    }
                }
            }
            if (rwdextraPrintInfo.getKllExperimentId() != null) {
                Long experimentId = Long.valueOf(rwdextraPrintInfo.getKllExperimentId());
                Experiment experiment = experimentMapper.loadById(experimentId);
                if (experiment != null) {
                    rwdextraPrintInfo.setKllztzypbh(experiment.getSampleId());
                    rwdextraPrintInfo.setKllztzwtbh(experiment.getExperimentNo());
                    /**试验台账对应试验项目信息*/
                    List<ExperimentDetail> experimentDetailList = experimentDetailMapper.selectByExperimentId(experimentId, TestProjectEnum.CONCRETE_PARAM_XNBG_LLZHL.getCode());
                    if (CollectionUtil.isNotEmpty(experimentDetailList)) {
                        /**将json转成对象*/
                        ConcreteXnbgLlzhl concreteXnbgLlzhl = experimentDetailList.get(0).getObjJson().toJavaObject(ConcreteXnbgLlzhl.class);
                        rwdextraPrintInfo.setKllztzjl(concreteXnbgLlzhl.getDxjl());
                    }
                }
            }

            /** 出厂证明签发日期 赋值  **/
            /** 如果有抗渗 任务单最后一车实际生产日期+配合比龄期加 （P6）,4(P8),5(P10),6(P12)  **/
            Date itemorderDate = itemorderMapper.selectByFrwdhCreateTimeMax(frwdh);
            String ksdj = null;
            if (StringUtils.isNotBlank(rwdextraPrintInfo.getKsdj())) {
                ksdj = rwdextraPrintInfo.getKsdj();
            }
            if (itemorderDate != null) {
                int dateNum;
                int lq = Integer.parseInt(mixProportion.getProportionLq());
                if (rwdextraPrintInfo.getKsExperimentId() != null && org.apache.commons.lang3.StringUtils.isNotBlank(ksdj)) {
                    dateNum = lq + KsLqEnum.selectByName(ksdj).getLq();
                } else {
                    dateNum = lq;
                }
                rwdextraPrintInfo.setCczmqfrq(DateHelper.addDateTime(itemorderDate, Calendar.DATE, dateNum, "yyyy-MM-dd"));
            } else {
                /** 如果任务单未生产,置空 **/
                rwdextraPrintInfo.setCczmqfrq("");
            }

            /*if (rwdextraPrintInfo.getKsExperimentId() != null) {
             *//** 如果有抗渗 取抗渗报告日期 +1天  **//*
                Experiment experiment = experimentMapper.loadById(rwdextraPrintInfo.getKsExperimentId());
                if (experiment != null && experiment.getReportDate() != null) {
                    rwdextraPrintInfo.setCczmqfrq(DateHelper.formatDateTimeDefaultFormat(experiment.getReportDate()));
                } else {
                    rwdextraPrintInfo.setCczmqfrq("");
                }
            } else {
                rwdextraPrintInfo.setCczmqfrq("");
            }
            if (StringUtils.isBlank(rwdextraPrintInfo.getCczmqfrq())) {
                if (CollectionUtil.isNotEmpty(kyExperimentIdList)) {
                    *//** 如果抗渗没有 取抗压报告 报告日期最大一条 报告日期+1天  **//*
                    Date entrustTime = experimentMapper.getMaxExperimentEntrustTime(kyExperimentIdList);
                    if (entrustTime != null) {
                        rwdextraPrintInfo.setCczmqfrq(DateHelper.formatDateTimeDefaultFormat(entrustTime));
                    }
                }
            }*/
        }
        rwdextraExtend.setRwdextraPrintInfo(rwdextraPrintInfo);
        rwdextraExtend.setPrintJson(JsonUtils.beanToObject(rwdextraPrintInfo));
        return rwdextraExtend;
    }

    @Override
    public List<Rwdextra> getAll(Rwdextra entity) {
        List<Rwdextra> list = rwdextraMapper.getList(entity);
        this.payloadOtherInfoList(list);
        return list;
    }

    @Override
    public Rwdextra selectByFrwdh(Integer fRwdh) {
        Rwdextra rwdextra = rwdextraMapper.selectByFrwdh(fRwdh);
        if (rwdextra != null) {
            RwdextraInfo rwdextraInfo = RwdextraInfo.jsonToObj(rwdextra.getExtrainfo());
            rwdextra.setRwdextraInfo(rwdextraInfo);

            RwdextraExtend rwdextraExtend = rwdextraExtendMapper.selectByFRwdh(fRwdh);
            if (rwdextraExtend != null) {
                rwdextra.setRwdextraExtend(rwdextraExtend);
            } else {
                rwdextraExtend = new RwdextraExtend().setFrwdh(fRwdh);
                rwdextraExtendMapper.insertSelective(rwdextraExtend);
                rwdextra.setRwdextraExtend(rwdextraExtend);
            }
            /**组装其它信息*/
            this.payloadOtherInfoList(Collections.singletonList(rwdextra));
        }
        return rwdextra;
    }

    @Override
    public void uploadBatch(RwdextraEntity entity) {
        assertTrue(CollectionUtil.isEmpty(entity.getFrwdhs()), "未选择任务单");
        for (Integer frwdh : entity.getFrwdhs()) {
            Rwdextra rwdextra = selectByFrwdh(frwdh);
            /**新增任务单并上传到协会   新增操作到协会*/
            RwdextraExtend rwdextraExtend = rwdextra.getRwdextraExtend();//品控任务单扩展信息
            RwdextraInfo rwdextraInfo = rwdextra.getRwdextraInfo();
            assertTrue(rwdextraInfo == null, "ERP任务单扩展信息不允许为空！");
            assertTrue(rwdextraInfo.getFHtdw() == null || rwdextraInfo.getFHtdw().isEmpty(), "施工单位不允许为空！");
            assertTrue(rwdextraInfo.getFGcmc() == null || rwdextraInfo.getFGcmc().isEmpty(), "工程名称不允许为空！");
            try {
                taskListLaboratoryService.insertProduceHnt(rwdextra, null, true);
            } catch (Exception e) {
                log.error("上传协会任务单失败：" + e.getMessage(), e);
                //任务单扩展表   记录失败原因
                rwdextraExtend.setReason(e.getMessage()).setStatus("0").setUpdateTime(new Date());
                rwdextraExtendMapper.updateByPrimaryKeySelective(rwdextraExtend);
            }
        }
    }


    @Override
    @Async
    public void genPrintInfo(List<Integer> frwdhs) {
        log.info("开始生成打印资料，入参：【{}】", JSON.toJSONString(frwdhs));
        if (frwdhs.isEmpty()) {
            return;
        }
        for (Integer frwdh : frwdhs) {
            Rwdextra rwdextra = this.selectByFrwdh(frwdh);
            assertTrue(rwdextra == null, "任务单信息不存在");

            List<String> experimentIds = new ArrayList();
            /**第一步先修改配合比*/
            rwdextraExtendService.setRwdextraPrintInfoPhb(rwdextra);
            RwdextraExtend entity = rwdextra.getRwdextraExtend() == null ? new RwdextraExtend() : rwdextra.getRwdextraExtend();
            RwdextraPrintInfo rwdextraPrintInfo = entity.getPrintJson() == null ? new RwdextraPrintInfo() : JsonUtils.getObject(entity.getPrintJson(), RwdextraPrintInfo.class);
            /** 更新任务单氯离子字段 **/
            String llzhl = RwdextraInfo.getFtbjValueKllz(rwdextra.getRwdextraInfo().getFTbj());
            if (StringUtils.isNotBlank(llzhl)) {
                entity.setLlzHl(llzhl);
                rwdextraPrintInfo.setLlzhl(llzhl);
            }
            /**重新查询所有关联的实验台账进行赋值**/
            /** 抗压 存在多个**/
            List<Long> kyExperimentIdList = experimentDetailMapper.selectExperimentIdByTestProjectCode(frwdh, CheckEnum.BATCH.getCode(), TestProjectEnum.CONCRETE_PARAM_KYQD.getCode());
            if (!kyExperimentIdList.isEmpty()) {
                List<String> kytzList = new ArrayList();
                List<RwdextraPrintInfo.Kytz> kyInfoList = new ArrayList();
                for (Long experimentId : kyExperimentIdList) {
                    RwdextraPrintInfo.Kytz kytz = new RwdextraPrintInfo.Kytz();
                    Experiment experiment = experimentMapper.loadById(experimentId);
                    if (experiment != null) {
                        if (StringUtils.isNotBlank(experiment.getSampleId())) {
                            kytzList.add(experiment.getSampleId());
                        } else {
                            kytzList.add(experiment.getExperimentNo());
                        }
                        kytz.setWtbh(experiment.getExperimentNo());
                        kytz.setXhwtbh(experiment.getConsignId());
                        kytz.setYpbh(experiment.getSampleId());
                        kytz.setSytzbh(String.valueOf(experiment.getId()));
                        List<ExperimentDetail> experimentDetailList = experimentDetailMapper.selectByExperimentId(experimentId, TestProjectEnum.CONCRETE_PARAM_KYQD.getCode());
                        if (CollectionUtil.isNotEmpty(experimentDetailList)) {
                            /**将json转成对象*/
                            ConcreteKyqd concreteKyqd = experimentDetailList.get(0).getObjJson().toJavaObject(ConcreteKyqd.class);
                            kytz.setQdpjz(concreteKyqd.getPjz28d());
                            kytz.setDdsjqd(concreteKyqd.getFyxs28d());
                            kytz.setZsbzqd(concreteKyqd.getZsbzqd28d());
                        }
                        kyInfoList.add(kytz);
                    }
                    rwdextraPrintInfo.setKytzList(kytzList);
                    rwdextraPrintInfo.setKyInfoList(kyInfoList);
                    experimentIds.add(String.valueOf(experimentId));
                }
            }
            /** 抗渗 只取一个 默认取计划时间最近一次试验台账**/
            List<Long> ksExperimentIdList = experimentDetailMapper.selectExperimentIdByTestProjectCode(frwdh, CheckEnum.BATCH.getCode(), TestProjectEnum.CONCRETE_PARAM_KSDJ.getCode());
            if (!ksExperimentIdList.isEmpty()) {
                rwdextraPrintInfo.setKsExperimentId(ksExperimentIdList.get(0));
                experimentIds.add(String.valueOf(ksExperimentIdList.get(0)));
            }
            /** 抗折 只取一个 默认取计划时间最近一次试验台账**/
            List<Long> kzExperimentIdList = experimentDetailMapper.selectExperimentIdByTestProjectCode(frwdh, CheckEnum.BATCH.getCode(), TestProjectEnum.CONCRETE_PARAM_KZQD.getCode());
            if (!kzExperimentIdList.isEmpty()) {
                rwdextraPrintInfo.setKzExperimentId(kzExperimentIdList.get(0));
                experimentIds.add(String.valueOf(kzExperimentIdList.get(0)));
            }
            /** 抗氯离子 只取一个 默认取计划时间最近一次试验台账**/
            String projectName = rwdextra.getRwdextraInfo().getFGcmc();
            String proportionPhb = rwdextra.getPhbshow();
            String year = rwdextra.getRwdextraInfo().getFRwno().substring(0, 4);
            List<Long> kllzExperimentIdList = experimentDetailMapper.selectExperimentIdByTestProjectCode(frwdh, CheckEnum.BATCH.getCode(), TestProjectEnum.CONCRETE_PARAM_XNBG_LLZHL.getCode());
            if (!kllzExperimentIdList.isEmpty()) {
                log.info("存在氯离子绑定台账的任务单【{}】", frwdh);
                rwdextraPrintInfo.setKllExperimentId(kllzExperimentIdList.get(0));
            } else {
                kllzExperimentIdList = experimentDetailMapper.selectExperimentIdByTestProjectCodeRwd(TestProjectEnum.CONCRETE_PARAM_XNBG_LLZHL.getCode(), proportionPhb, projectName, year);
                if (!kllzExperimentIdList.isEmpty()) {
                    rwdextraPrintInfo.setKllExperimentId(kllzExperimentIdList.get(0));
                    log.info("不存在氯离子绑定台账的任务单【{}】 绑定试验台账ID :【{}】", frwdh, kllzExperimentIdList);
                } else {
                    log.info("未找到氯离子绑定台账的任务单【{}】", frwdh);
                }
            }
            entity.setPrintJson(JsonUtils.beanToObject(rwdextraPrintInfo));
            /** 重新更新原材料 和 混凝土台账信息 **/
            if (null != rwdextraPrintInfo.getMixProportionInfo() && null != rwdextraPrintInfo.getMixProportionInfo().getProportionMaterial() && !rwdextraPrintInfo.getMixProportionInfo().getProportionMaterial().isEmpty()) {
                MixProportionReport mixProportionReport = JsonUtils.getObject(rwdextraPrintInfo.getMixProportionInfo().getProportionMaterial(), MixProportionReport.class);
                if (null != mixProportionReport.getSn() && StringUtils.isNotBlank(mixProportionReport.getSn().getPktzid())) {
                    experimentIds.add(String.valueOf(mixProportionReport.getSn().getPktzid()));
                }
                if (null != mixProportionReport.getKzf() && StringUtils.isNotBlank(mixProportionReport.getKzf().getPktzid())) {
                    experimentIds.add(String.valueOf(mixProportionReport.getKzf().getPktzid()));
                }
                if (null != mixProportionReport.getFmh() && StringUtils.isNotBlank(mixProportionReport.getFmh().getPktzid())) {
                    experimentIds.add(String.valueOf(mixProportionReport.getFmh().getPktzid()));
                }
                if (null != mixProportionReport.getCgl() && StringUtils.isNotBlank(mixProportionReport.getCgl().getPktzid())) {
                    experimentIds.add(String.valueOf(mixProportionReport.getCgl().getPktzid()));
                }
                if (null != mixProportionReport.getXgl() && StringUtils.isNotBlank(mixProportionReport.getXgl().getPktzid())) {
                    experimentIds.add(String.valueOf(mixProportionReport.getSn().getPktzid()));
                }
                if (null != mixProportionReport.getWjj1() && StringUtils.isNotBlank(mixProportionReport.getWjj1().getPktzid())) {
                    experimentIds.add(String.valueOf(mixProportionReport.getWjj1().getPktzid()));
                }
                if (null != mixProportionReport.getWjj2() && StringUtils.isNotBlank(mixProportionReport.getWjj2().getPktzid())) {
                    experimentIds.add(String.valueOf(mixProportionReport.getWjj2().getPktzid()));
                }
            }
            /*
            if (CollectionUtil.isNotEmpty(experimentIds)) {
                try {
                    uploadAndDownloadAssociationService.downloadLaboratory(new UploadLaboratoryEntity().setExperimentId(experimentIds));
                } catch (Exception e) {
                    log.error("从协会下载数据失败,错误信息：【{}】", e.getMessage(), e);
                }
            }*/
            MixProportion mixProportion = mixProportionMapper.selectByPhbNo(proportionPhb);
            OpenAppraisal openAppraisal = openAppraisalMapper.selectByItemOrder(year, projectName, proportionPhb);
            if (openAppraisal != null) {
                /**更新任务单开盘鉴定编号**/
                entity.setOpenAppraisalId(openAppraisal.getId());
                /** 判断开盘鉴定中是否存在配合比信息，没有补全对应信息 **/
                RwdextraPrintInfo rwdextraPrintInfoOpen = JsonUtils.getObject(openAppraisal.getPrintJson(), RwdextraPrintInfo.class);
                if (rwdextraPrintInfoOpen != null && rwdextraPrintInfoOpen.getMixProportionInfo() == null) {
                    if (mixProportion == null) {
                        log.info("重新生产开盘鉴定信息 配合比编号不存在 【{}】", proportionPhb);
                    }
                    Rwdextra rwdextraOpen = rwdextraMapper.selectByFrwdh(openAppraisal.getFrwdh());
                    if (rwdextraOpen != null) {
                        this.payloadOtherInfoList(Collections.singletonList(rwdextraOpen));
                    }
                    rwdextraExtendService.setMixProportionPktzId(mixProportion, rwdextraOpen);
                    rwdextraPrintInfoOpen.setMixProportionInfo(mixProportion);
                    openAppraisal.setPrintJson(JsonUtils.beanToObject(rwdextraPrintInfoOpen));
                }
                openAppraisalMapper.updateByPrimaryKeySelective(openAppraisal);
            } else {
                OpenAppraisalDto openAppraisalDto = new OpenAppraisalDto().setFphbNo(proportionPhb).setFgcmc(projectName).setFrwno(year);
                openAppraisal = openAppraisalService.initOpenAppraisal(openAppraisalDto);
                /** 有可能存在同工程同配合比的任务单还未生产，所以匹配不到开票鉴定，也生成不了 */
                if (openAppraisal != null) {
                    entity.setOpenAppraisalId(openAppraisal.getId());
                }
            }
            /** 重新设置签名*/
            rwdextraPrintInfo.setSignature(signatureMapper.loadById(1L));
            /** 配合比调整记录更新*/
            Phbhistory phbhistory = phbhistoryService.selectByRwdhAndTime(frwdh, mixProportion, 0);
            rwdextraPrintInfo.setPhbhistory(phbhistory);
            List<Phbhistory> phbhistoryList = new ArrayList();
            List<Itemorder> itemorderList = itemorderMapper.selectByFrwdh(frwdh);
            for (Itemorder itemorder : itemorderList) {
                /** 查询小于小票创建时间的调整记录*/
                Phbhistory phbhistoryNew = phbhistoryService.selectByRwdhAndPhbOne(frwdh, mixProportion,itemorder.getItid(),itemorder.getMixtable());
                /** 如果存在入已入库的调整记录，则不保存*/
                if(!phbhistoryList.stream().anyMatch(h -> h.getPhid() != null && h.getPhid().equals(phbhistoryNew.getPhid()))){
                    phbhistoryList.add(phbhistoryNew);
                }
            }
            phbhistoryService.sortPhbhistoryList(phbhistoryList, mixProportion);
            rwdextraPrintInfo.setPhbhistoryList(phbhistoryList);
            entity.setPrintJson(JsonUtils.beanToObject(rwdextraPrintInfo));
            if (rwdextra.getFhquantity() > 0) {
                /** 判断是否存在质量证明书编号*/
                if (StringUtils.isBlank(entity.getQualityCertificateNo())) {
                    entity.setQualityCertificateNo(UidUtils.genNoNumber(GenerateCodeEnum.QUALITY_CERTIFICATE.getCode(), "%05d"));
                }
                /** 判断是否存在供应开始时间*/
                if (entity.getSupplyStartTime() == null) {
                    entity.setSupplyStartTime(itemorderMapper.selectByFrwdhCreateTimeMax(frwdh));
                    entity.setSupplyEndTime(itemorderMapper.selectByFrwdhCreateTimeMin(frwdh));
                }
            }
            /** 配合比调整记录更新*/
            rwdextraExtendMapper.updateByPrimaryKeySelective(entity);
        }
    }

    @Override
    public void updateBatchPrintLlzhl() {
        /** 查询25年后的任务单 **/
        List<Rwdextra> rwdextraList = rwdextraMapper.getList(new Rwdextra().setPlantimeStart("2025-01-01"));
        for (Rwdextra rwdextra : rwdextraList) {
            Integer frwdh = rwdextra.getFrwdh();
            RwdextraExtend entity = rwdextraExtendMapper.selectByFRwdh(frwdh);
            if (entity == null) {
                continue;
            }
            RwdextraPrintInfo rwdextraPrintInfo = entity.getPrintJson() == null ? new RwdextraPrintInfo() : JsonUtils.getObject(entity.getPrintJson(), RwdextraPrintInfo.class);
            /** 抗氯离子 只取一个 默认取计划时间最近一次试验台账**/
            List<Long> kllzExperimentIdList = experimentDetailMapper.selectExperimentIdByTestProjectCode(frwdh, CheckEnum.BATCH.getCode(), TestProjectEnum.CONCRETE_PARAM_XNBG_LLZHL.getCode());
            if (!kllzExperimentIdList.isEmpty()) {
                log.info("存在氯离子绑定台账的任务单【{}】", frwdh);
                rwdextraPrintInfo.setKllExperimentId(kllzExperimentIdList.get(0));
            } else {
                RwdextraInfo rwdextraInfo = RwdextraInfo.jsonToObj(rwdextra.getExtrainfo());
                String projectName = rwdextraInfo.getFGcmc();
                String proportionPhb = rwdextra.getPhbshow();
                String year = rwdextraInfo.getFRwno().substring(0, 4);
                kllzExperimentIdList = experimentDetailMapper.selectExperimentIdByTestProjectCodeRwd(TestProjectEnum.CONCRETE_PARAM_XNBG_LLZHL.getCode(), proportionPhb, projectName, year);
                log.info("不存在氯离子绑定台账的任务单【{}】 绑定试验台账ID :【{}】", frwdh, kllzExperimentIdList);
            }
            if (CollectionUtil.isNotEmpty(kllzExperimentIdList)) {
                rwdextraPrintInfo.setKllExperimentId(kllzExperimentIdList.get(0));
            }
            entity.setPrintJson(JsonUtils.beanToObject(rwdextraPrintInfo));
            rwdextraExtendMapper.updateByPrimaryKeySelective(entity);
        }
    }
}
